<template>
  <div class="update-name" style="padding: 10px">
    <!-- 导航栏 -->
    <van-nav-bar
      title="设置昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onUpdateName"
    />
    <!-- /导航栏 -->
    <van-field
      class="field-wrap"
      v-model="nickname"
      rows="2"
      autosize
      type="textarea"
      maxlength="7"
      placeholder="请输入新昵称"
      show-word-limit
    />
  </div>
</template>

<script>
import { updateUserProfile } from "@/api/user.js";
export default {
  props: ["value"],
  data() {
    return {
      nickname: this.value, //新昵称
    };
  },
  methods: {
    async onUpdateName() {
      this.$toast.loading({
        message: "保存中...",
        forbidClick: true,
        duration: 0,
      });
      try {
        //   非空校验
        if (this.nickname.trim() === "") return this.$toast("请输入昵称");
        // 发起请求 改什么传什么参数
        await updateUserProfile({
          name: this.nickname,
        });
        // 传给父组件中的v-model
        this.$emit("input", this.nickname);
        // 退出弹出层
        this.$emit("close");
        this.$toast.success("更新成功");
      } catch (err) {
        if (err.response && err.response.status === 401) {
          return this.$toast("用户未认证");
        }
        this.$toast("更新失败");
      }
    },
  },
};
</script>

<style scoped>
.field-wrap {
  margin-top: 12px;
  padding: 10px;
}
</style>